package org.ans.jpodcast.client;

import java.io.IOException;
import org.ans.jpodcast.auth.PreemptiveAuthHttpClientInterceptor;
import org.ans.jpodcast.responsehandler.InfoResponseHandler;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * This class handles the connection with Podcast Producer.
 * You can create PcPWorkflow objects with this class.
 * @author Andy Sykes
 */
public class PcPConnection {

    private String serverName;
    private Integer serverPort;
    private String username;
    private String password;

    private PcPProperties pcpProperties;

    private DefaultHttpClient httpClient;

    public void connect() throws IOException {

        // Check to see if we have a valid httpClient we can reuse
        if (httpClient == null) {
            httpClient = new DefaultHttpClient();
        }

        // Install the very permissive hostname validator for SSLSocketFactory
        // Reason for doing this is PcP generates a certificate with the hostname "default"
        SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());

        // Add our preemptive auth interceptor and prepare auth scheme
        httpClient.addRequestInterceptor(new PreemptiveAuthHttpClientInterceptor(), 0);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(serverName, serverPort),
                new UsernamePasswordCredentials(username, password));

        HttpGet infoGet = new HttpGet("https://" + serverName + ":" + serverPort + "/podcastproducer/info");

        HttpResponse response = httpClient.execute(infoGet);
        InfoResponseHandler handler = new InfoResponseHandler();
        setPcpProperties(handler.handleResponse(response));

    }

    public void setServerName(String serverName) {
        this.serverName = serverName;
    }

    public void setServerPort(Integer serverPort) {
        this.serverPort = serverPort;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * @return the properties associated with the server we are connecting to. Returns null if
     * we aren't connected to a server.
     */
    public PcPProperties getPcpProperties() {
        return pcpProperties;
    }

    public void setPcpProperties(PcPProperties pcpProperties) {
        this.pcpProperties = pcpProperties;
    }
}
